package edu.lnu.ums.dal.impl;

import java.util.List;

import edu.lnu.ums.dal.IGenericDictionaryDAO;
import edu.lnu.ums.entities.core.AbstractEntity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public abstract class GenericDictionaryDAO<T extends AbstractEntity> extends AbstractNoConcurrentAccessGenericDAO<T> implements IGenericDictionaryDAO<T>{
    
    public GenericDictionaryDAO(Class<T> cls) {
        super(cls);
    }

    @Override
    public void delete(T obj) {
        throw new UnsupportedOperationException("You can not delete records from dictionaries!");
    }

    @SuppressWarnings("unchecked")
    @Override
    public final T getByName(EntityManagerFactory factory, String name) {
        EntityManager em = factory.createEntityManager();

        List<T> objects = em.createQuery(getByNameQuery())
                .setParameter("name", name).getResultList();
        em.close();
        setEntityManagerFactoryToEntityList(factory, objects);
        
        if (objects.size() == 0) {
            return null;
        }

        if (objects.size() > 2) {
            throw new RuntimeException("Can not be two objects with same name");
        }

        return objects.get(0);
    }
    
    public abstract String getByNameQuery();
}
